/*
 * Module name : StockOperationComponent
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';

import ButtonModel from '../../../../base/models/ButtonModel.js';
import ButtonWidget from '../../../../widgets/ButtonWidget.js'
import { ajax_call } from '../../../../tools.js';

import StockOperationModel from '../../../models/StockOperationModel.js';
import StockOperationView from './StockOperationView.js';
import StockOperationForm from './StockOperationForm.js';

const template = require('./templates/StockOperationComponent.mustache');

const StockOperationCollectionView = Mn.CollectionView.extend({
    tagName: 'tbody',
    childView: StockOperationView,
    childViewTriggers:{
        'model:edit': 'model:edit',
        'model:delete': 'model:delete'
    }
});

const StockOperationComponent = Mn.View.extend({
    tagName: "fieldset",
    className: "separate_block border_left_block",
    template: template,
    regions: {
        current_stock: '.current_stock',
        list: {el: 'tbody', replaceElement: true},
        addButton: '.add',
        popin: '.popin',
    },
    ui: {},
    bb_sync: true,
    // Listen to the current's view events
    events: {},
    // Listen to collection events
    collectionEvents: {
        'add': 'showCurrentStock',
        'change': 'showCurrentStock',
    },
    childViewEventPrefix: 'stock:operation',
    // Listen to child view events
    childViewEvents: {
        'action:clicked': "onActionClicked",
        'cancel:form': 'render',
        'destroy:modal': 'render',
        'model:edit': 'onModelEdit',
        'model:delete': 'onModelDelete',
    },
    // Bubble up child view events
    childViewTriggers: {
    },
    initialize(){
        this.config = Radio.channel('config');
        this.app = Radio.channel('app');
    },
    showCurrentStock(){
        let this_ = this;
        ajax_call(
            this.collection.url().replace("/stock_operations", "?action=get_current_stock"),
            {},
            'GET',
            {
                success: function(result) {
                    if(result !== "") {
                        this_.$('.current_stock').show();
                        this_.$('table').show();
                        this_.showChildView(
                            'current_stock',
                            "<h3 class='highlight'>Stock actuel : "+result+"</h3>"
                        );
                    }else{
                        this_.$('.current_stock').hide();
                        this_.$('table').hide();
                    }
                }
            }
        );
    },
    showAddButton(){
        let model = new ButtonModel({
            label: "Mouvement de stock",
            icon: "plus",
            action: "add"
        });
        let view = new ButtonWidget({model: model});
        this.showChildView('addButton', view);
    },
    showModelForm(model, edit){
        let view = new StockOperationForm(
            {
                model: model,
                edit:edit,
                destCollection: this.collection,
                bb_sync: this.bb_sync
            }
        );
        this.app.trigger('show:modal', view);
    },
    onRender(){
        let view = new StockOperationCollectionView({collection: this.collection});
        this.showChildView('list', view);
        this.showAddButton();
        this.showCurrentStock();
    },
    templateContext(){
        return {};
    },
    onActionClicked(action){
        if (action == 'add'){
            let model = new StockOperationModel();
            this.showModelForm(model, false);
        }
    },
    onModelEdit(model, childView){
        this.showModelForm(model, true);
    },
    onModelDelete(model, childView){
        var result = window.confirm("Êtes-vous sûr de vouloir supprimer ce mouvement de stock ?");
        if (result){
            childView.model.destroy(
                {
                    success: this.onModelDeleteSuccess.bind(this),
                    error: this.onModelDeleteError.bind(this),
                    wait: true
                }
            );
        }
    },
    onModelDeleteSuccess: function(){
        this.showCurrentStock();
    },
    onModelDeleteError: function(){
        let messagebus = Radio.channel('message');
        messagebus.trigger('error', this,
                           "Une erreur a été rencontrée lors de la " +
                           "suppression du mouvement de stock");
    },
});
export default StockOperationComponent
